package com.ruoyi.web.controller.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.web.controller.auth.GiteeService;
import com.ruoyi.web.controller.dos.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author mr.huang [jie88888822@163.com]
 * @devTime 2022-06-10
 */
@Controller
@Slf4j
@RequestMapping("/auth")
public class AuthController {
	@Resource
	private GiteeService giteeService;

	/**
	 * 请求授权页面
	 */
	@GetMapping(value = "/toGiteeServerAuthentication")
	public void qqAuth(HttpSession session, HttpServletResponse resp) throws IOException {
		// Step1：获取Authorization Code   系那个Gitee发送认证
		resp.sendRedirect(giteeService.authorizeUri());
	}

	@GetMapping("/snsLogin")
	public AjaxResult snsLogin(String code, String state) throws Exception {
		log.info("code：{}",code);
		log.info("state：{}",state);
		// Step3: 获取用户信息
		JSONObject userInfo = giteeService.getUserInfo(giteeService.getAccessToken(code));
		/**
		 * 获取到用户信息之后，就该写你自己的业务逻辑了
		 */
		UserInfo user = JSON.parseObject(userInfo.toString(), UserInfo.class);
		log.debug("用户信息：{}",user);
		if (user == null) {
			throw new Exception("网络不太通畅，无法获取远程" + user + "数据");
		} else {
			return /*AjaxResult.success(loginService.oauth2Login(user));*/ null;
		}
	}
}
